const path = require('path');
const koa = require('koa')
const { koaBody } = require('koa-body');
const app = new koa()
const nunjucks = require('koa-nunjucks-2')
const koaStatic = require('koa-static')

const web = require("./router/web")
const api = require("./router/api")
const config = require('./config')

app.use(koaStatic(__dirname + '/public'));

app.use(koaBody({
    enableTypes: ['json', 'form', 'text'],
    multipart: true // 是否支持 multipart-formdate 的表单
}));

app.use(nunjucks({
    ext: 'html',
    path: path.join(__dirname, 'views'),// 指定视图目录
    nunjucksConfig: {
        trimBlocks: true, // 开启转义 防Xss
        autoescape: true,
        watch: true
    }
}));
app.use(async (ctx, next) => {
    const start = new Date()
    await next()
    const ms = new Date() - start
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
});


/**
 * router.routers() 启动路由
 * router.allowedMethods() 运行任何请求 --- get/post/put/delete等
 */
app.use(web.routes(), web.allowedMethods())
app.use(api.routes(), api.allowedMethods())

const hostName = config.ip; //ip
const port = config.port; //端口
app.listen(port, hostName)  //http://localhost:3031
console.log(`运行网址：http://localhost:${port}`);